package com.vrsys.controller;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.vrsys.domain.LineItem;
import com.vrsys.domain.Order;
import com.vrsys.domain.session.Cart;

@Controller
@RequestMapping("/cart")
public class CartController extends BaseController {
    @Autowired
    private Cart cart;

    @RequestMapping(value = "/cartlist.od", method = RequestMethod.GET)
    public ModelAndView queryProducts(ModelAndView mv) {
        mv.addObject("products", cart.getProducts());
        mv.addObject("amount", cart.getAmount());
        mv.setViewName("cartlist");
        return mv;
    }

    @RequestMapping(value = "/{pid}/removeproduct.od", method = RequestMethod.POST)
    public @ResponseBody void removeFromCart(@PathVariable("pid") int pId) {
        cart.removeProduct(pId);
    }

    @RequestMapping(value = "/submitcart.od", method = RequestMethod.POST)
//    public ModelAndView submitCartToOrder(List<LineItem> items, ModelAndView mv) {
    public ModelAndView submitCartToOrder(Order order, ModelAndView mv) {
        BigDecimal amount = new BigDecimal(0);
        if(null != order.getLines()) {
            for(LineItem i : order.getLines()) {
                LineItem item = cart.getLineItem(i.getProduct().getProductId());
                item.setProductQty(i.getProductQty());
                amount = amount.add(item.getProduct().getUnitPrice().multiply(new BigDecimal(i.getProductQty()), Cart.mc));
            }
            cart.setAmount(amount);
            mv.setViewName("redirect:/order/ordergener.od");
            return mv;
        } else {
            mv.setViewName("commonerror");
            mv.addObject("errorMsgCode", "cartEmpty");
            return mv;
        }
    }
}
